import { TTenantType } from '@/datatypes/tTenant/data';
import { handleAdd, handleRemove, handleRemoveList, handleUpdate, page } from '@/services';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';

import { UserStatusValueEnum } from '@/enums/auth';
import UpdateForm from '@/pages/tenant/tTenant/components/UpdateForm';
import { tTenantUrl } from '@/urls';
import { Button, Drawer, Image } from 'antd';
import React, { useRef, useState } from 'react';

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TTenantType>();
  const [selectedRowsState, setSelectedRows] = useState<TTenantType[]>([]);

  const columns: ProColumns<TTenantType>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '租户名',
      dataIndex: 'name',
    },
    {
      title: '电话',
      dataIndex: 'phone',
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      hideInSearch: true,
      render: (avatar: React.ReactNode) => (
        <Image
          src={typeof avatar === 'string' ? avatar : ''}
          alt="头像"
          width={40}
          height={40}
          style={{ borderRadius: '50%' }}
        />
      ),
    },

    {
      title: '用户状态',
      dataIndex: 'status',
      valueEnum: UserStatusValueEnum,
    },

    {
      title: '用户备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '最后登陆',
      dataIndex: 'lastLoginTime',
      hideInSearch: true,
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
            setShowDetail(false);
          }}
        >
          更新
        </a>,
        <a
          key="remove"
          onClick={async () => {
            await handleRemove(tTenantUrl, record.id);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
            setShowDetail(false);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<TTenantType, API.PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => page(tTenantUrl, params)}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveList(tTenantUrl, selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建"
        width="400px"
        open={createModalVisible}
        onOpenChange={handleModalVisible}
        onFinish={async (value: any) => {
          const success = await handleAdd(tTenantUrl, value as TTenantType);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '租户名为必填项',
            },
          ]}
          width="md"
          name="name"
          label={'租户名'}
          placeholder={'请输入租户名'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '电话为必填项',
            },
          ]}
          width="md"
          name="phone"
          label={'电话'}
          placeholder={'请输入电话'}
        />

        <ProFormText
          rules={[
            {
              required: true,
              message: '用户备注为必填项',
            },
          ]}
          width="md"
          name="remark"
          label={'用户备注'}
          placeholder={'请输入用户备注'}
        />

        <ProFormSelect
          rules={[
            {
              required: true,
              message: '用户状态',
            },
          ]}
          width="md"
          name="status"
          label={'用户状态'}
          valueEnum={UserStatusValueEnum}
          placeholder={'请输入用户状态'}
        />

      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(tTenantUrl, value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<TTenantType>
            column={2}
            title={currentRow?.id}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<TTenantType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
